import { login } from '@/api/user'
import { setToken as setToken2, getToken, removeToken } from '@/utils/auth'
import { getUserProfileApi, getUserInfoByIdApi } from '@/api/user'
import store from '@/store'
// import {} from './permission'
// import {resetRouter} from '@/router/index'
// import { reject, resolve } from 'core-js/fn/promise'
const state = {
  // 在state中声明token变量
  // 只要不刷新就从vuex里面读取值，刷新才从cookie里面读取值
  token: getToken() || '',
  userInfo: {}
}
// 在mutations中声明一个修改token的方法
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    // 设置了 token 的同时, 同步到本地cookies中
    setToken2(newToken)
  },
  userInfo(state, newUserinfo) {
    state.userInfo = newUserinfo
  },
  // 退出登录
  logOut(state) {
    state.token = ''
    state.userInfo = {}
    store.commit('permission/setRoutes', [])
    removeToken()
  }
}

// 在actions中调用后端接口
const actions = {
  async getToken(state, data) {
    // return new Promise()
    // return new Promise((resolve, reject) => {
    //   login(data).then((res) => {
    //     state.commit('setToken', res.data)
    //     resolve(res)
    //   }).catch(err => {
    //     console.log(err.message)
    //     reject(err)
    //   })
    // })
    const res = await login(data)
    state.commit('setToken', res.data)
    return res
  },
  async userInfo(state) {
    const res = await getUserProfileApi()
    const res2 = await getUserInfoByIdApi(res.data.userId)
    // console.log(res2, 'res2')
    const baseResult = {
      ...res.data,
      ...res2.data
    }
    state.commit('userInfo', baseResult)
    console.log(baseResult)
    return baseResult
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

